/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.purpose.service.impl;

import com.koron.common.bean.StaffBean;
import com.koron.common.generator.DefaultIdGenerator;
import com.koron.purpose.bean.SafetyOrgVo;
import com.koron.purpose.domain.SafetyOrg;
import com.koron.purpose.domain.SafetyOrgStaff;
import com.koron.purpose.mapper.SafetyOrgMapper;
import com.koron.purpose.mapper.SafetyOrgStaffMapper;
import com.koron.purpose.service.api.SafetyOrgService;
import org.koron.ebs.mybatis.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.swan.bean.MessageBean;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class SafetyOrgServiceImpl implements SafetyOrgService {

	private final Logger logger = LoggerFactory.getLogger(SafetyOrgServiceImpl.class);
	@SuppressWarnings("deprecation")
	@Override
	public MessageBean<?> insert(SafetyOrg bean, StaffBean user) {
		MessageBean<?> msg = MessageBean.create(0, "success", void.class);
		if(StringUtils.isEmpty(bean.getCorpCode()) || StringUtils.isEmpty(bean.getName())){
			msg.setCode(35001);
			msg.setDescription("参数校验异常");
			return msg;
		}
		SessionFactory factory = new SessionFactory();
		try {
			SafetyOrgMapper mapper = factory.getMapper(SafetyOrgMapper.class);
			Integer count = mapper.addVerification(bean.getName(),bean.getCorpCode(),bean.getPid());
			if(count > 0){
				factory.close(false);
				msg.setCode(35001);
				msg.setDescription("名称重复");
				return msg;
			}

			bean.setAddTime(new Date());
			bean.setAddUser(user.getCode());
			bean.setAddUserName(user.getName());
			bean.setUpdateTime(new Date());
			bean.setUpdateUser(user.getCode());
			bean.setUpdateUserName(user.getName());
			bean.setId(DefaultIdGenerator.getInstance().generateLongId());
			bean.setSubnumber(0);

			String pid = bean.getPid();
			if(StringUtils.isEmpty(pid)){
				String corpCode = bean.getCorpCode();
				count = factory.getMapper(SafetyOrgMapper.class).queryRoot(corpCode);
				if(count > 0){
					factory.close(false);
					msg.setCode(35001);
					msg.setDescription("上级节点参数异常");
					return msg;
				}
			}else{
				SafetyOrg parent = mapper.queryById(pid);
				if(parent == null){
					factory.close(false);
					msg.setCode(35001);
					msg.setDescription("上级节点参数异常");
					return msg;
				}
				int subnumber = parent.getSubnumber();
				subnumber++;
				parent.setSubnumber(subnumber);
				mapper.update(parent);  //更新父节点的子节点数量
			}
			mapper.insert(bean); //保存数据
			factory.close();
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			factory.close(false);
			msg.setCode(35001);
			msg.setDescription("数据库连接异常");
		}
		return msg;
	}

	@SuppressWarnings("deprecation")
	@Override
	public MessageBean<?> update(String id, String name,Integer ranking, StaffBean user) {
		MessageBean<?> msg = MessageBean.create(0, "success", void.class);
		SessionFactory factory = new SessionFactory();
		try {
			SafetyOrgMapper mapper = factory.getMapper(SafetyOrgMapper.class);
			SafetyOrg bean = mapper.queryById(id);
			if(bean == null){
				factory.close(false);
				msg.setCode(35001);
				msg.setDescription("参数校验异常");
				return msg;
			}
			Integer count = mapper.updateVerification(name, bean.getCorpCode(),bean.getPid(), id);
			if(count > 0){
				factory.close(false);
				msg.setCode(35001);
				msg.setDescription("名称重复");
				return msg;
			}
			bean.setUpdateTime(new Date());
			bean.setUpdateUser(user.getCode());
			bean.setUpdateUserName(user.getName());
			bean.setName(name);
			bean.setRanking(ranking);
			mapper.update(bean); //更新数据
			factory.close();
		} catch (Exception e) {
			factory.close(false);
			msg.setCode(35001);
			msg.setDescription("数据库连接异常");
		}
		return msg;
	}

	@SuppressWarnings("deprecation")
	@Override
	public MessageBean<?> delete(String id) {
		MessageBean<?> msg = MessageBean.create(0, "success", void.class);
		try(SessionFactory factory = new SessionFactory();){
			SafetyOrgMapper mapper = factory.getMapper(SafetyOrgMapper.class);
			Integer count = mapper.queryByPid(id);
			if(count > 0){
				msg.setCode(35002);
				msg.setDescription("存在下级节点，不能删除");
				return msg;
			}
			count = mapper.queryStaffCount(id);
			if(count > 0){
				msg.setCode(35002);
				msg.setDescription("已关联用户，不能删除");
				return msg;
			}
			mapper.delete(id);
		} catch (Exception e) {
			msg.setCode(35001);
			msg.setDescription("数据库连接异常");
		}
		return msg;
	}

	@SuppressWarnings({ "deprecation", "rawtypes" })
	@Override
	public MessageBean<?> list(String corpCode) {
		MessageBean<List> msg = MessageBean.create(0, "success", List.class);
		List<SafetyOrg> list = new ArrayList<>();
		try(SessionFactory factory = new SessionFactory();){
			SafetyOrgMapper mapper = factory.getMapper(SafetyOrgMapper.class);
			list = mapper.queryByCorp(corpCode);
			msg.setData(list);
		} catch (Exception e) {
			msg.setCode(35001);
			msg.setDescription("数据库连接异常");
		}
		return msg;
	}

	@SuppressWarnings("deprecation")
	@Override
	public MessageBean<?> tree(String corpCode) {
		MessageBean<SafetyOrg> msg = MessageBean.create(0, "success", SafetyOrg.class);
		List<SafetyOrg> list = new ArrayList<>();
		try(SessionFactory factory = new SessionFactory();){
			SafetyOrgMapper mapper = factory.getMapper(SafetyOrgMapper.class);
			list = mapper.queryByCorp(corpCode);
			SafetyOrg root = null;
			if(!list.isEmpty()){
				root = list.stream().filter(node -> node.getPid()==null).findAny().get();
				construct(root,list);
			}
			msg.setData(root);
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			msg.setCode(35001);
			msg.setDescription("数据库连接异常");
		}
		return msg;
	}

	@Override
	public MessageBean<?> mobileQuery(String corpCode, String orgId, String staffName) {
		MessageBean<List> msg = MessageBean.create(0, "success", List.class);
		List<SafetyOrgVo> list = new ArrayList<>();
		try(SessionFactory factory = new SessionFactory();){
			SafetyOrgMapper safetyOrgMapper = factory.getMapper(SafetyOrgMapper.class);
			SafetyOrgStaffMapper safetyOrgStaffMapper = factory.getMapper(SafetyOrgStaffMapper.class);
			List<SafetyOrg> safetyOrgs = safetyOrgMapper.queryByCorpAndPid(corpCode,orgId);
			for(SafetyOrg safetyOrg : safetyOrgs) {
				SafetyOrgVo vo = new SafetyOrgVo();
				List<SafetyOrgStaff> safetyOrgStaffs = safetyOrgStaffMapper.query(staffName, safetyOrg.getId(), null, null, null);
				vo.setOrg(safetyOrg);
				vo.setStaffs(safetyOrgStaffs);
				list.add(vo);
			}
			msg.setData(list);
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			msg.setCode(35001);
			msg.setDescription("数据库连接异常");
		}
		return msg;
	}

	private void construct(SafetyOrg root,List<SafetyOrg> list){
		List<SafetyOrg> collect = list.stream().filter(node -> root.getId().equals(node.getPid())).collect(Collectors.toList());
        if (null != collect && !collect.isEmpty()) {
            root.setChildList(collect);
            collect.forEach(grid -> construct(grid, list));
        }
	}

}
